import { Component, OnInit } from '@angular/core';
import { Router, NavigationExtras } from '@angular/router';
import { Md5 } from '../utils';

// 服务
import { AuthService } from '../auth/auth.service';
import { LoginService } from './login.service';

// 模型
import { LoginRequest } from './login';

@Component({
    moduleId: module.id,
    templateUrl: 'login.component.html'
})
export class LoginComponent implements OnInit {
    message: string;
    type: string;
    captchaID: string;
    captchaImg: string;
    login = new LoginRequest();

    ngOnInit(): void {
        // 获取验证码
        this.getCaptcha();
    }

    constructor(
        private authService: AuthService,
        private loginService: LoginService,
        private router: Router
    ) { }

    // 获取验证码
    getCaptcha(): void {
        this.loginService.queryCaptcha().then(res => {
            this.captchaID = res.captchaid;
            this.captchaImg = `/v1/auth/captcha/${this.captchaID}`;
        });
    };

    // 点击改变验证码
    change(): void {
        this.captchaImg = `/v1/auth/captcha/${this.captchaID}?reload=${Math.random()}`;
    }

    onSubmit() {
        const username = this.login.userName;
        let password = this.login.password;
        const captcha = this.login.captcha;
        if (!username || !password || !captcha) {
            this.message = '用户名或密码或验证码不能为空';
            this.type = 'warning';
            return;
        }
        password = Md5.hashStr(password).toString();
        console.log(`用户名:${this.login.userName}-密码:${this.login.password}`);

        this.loginService.login(username, password, captcha, this.captchaID).then(
            data => {
                console.log(`session_id:${data}`);
                this.authService.sessionID = data.token;
                if (!this.authService.redirectURL || this.authService.redirectURL === '/admin') {
                    this.router.navigate(['/']);
                } else {
                    const navigationExtras: NavigationExtras = {
                        preserveQueryParams: true,
                        preserveFragment: true
                    };
                    this.router.navigate([this.authService.redirectURL], navigationExtras);
                }

            },
            err => {
                console.log(err)
                this.message = err;
                this.type = 'danger';
                this.getCaptcha();
            }
        );
    }
}
